import Vue from 'vue'
import VueRouter from 'vue-router'
import Routes from './routers'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getKey, clearKey } from '@/utils/utils'

// 进度条
NProgress.configure({
  showSpinner: false
})


// 引入路由组件


Vue.use(VueRouter)

// 解决编程时路由跳转到当前路由(参数不变)，多次执行会抛出NavigationDuplicated的警告错误
// --声明是导航没有这类问题的，因为vue-router底层已经处理好了

// 先把VueRouter原型对象的push保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

// 重写push|replace
// 第一个参数：告诉原来push方法，你往哪里跳转（传递那些参数）
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        // call || apply区别：
        // 相通点，都可以调用函数一次，都可以篡改函数的上下文一次
        // 不同点，call与apply传递参数：call传递参数用逗号隔开，apply传递数组
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

const routes = Routes

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
// 使用 router.beforEach 注册一个全局前置守卫，判断用户是否登录
router.beforeEach((to, from, next) => {
  if (getKey('userinfo')) {
    // 已登录
    if (to.path === '/login' || to.path === '/') {
      clearKey()
      next()
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 未登录
    if (to.path === '/login' || to.path === '/') {
      next()
    } else {
      clearKey()
    next('/login')
    NProgress.done()
    }
  }
})

export default router
